﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Mvc.Models;
using PagedList;
using CubicFWNet.Common.Excel;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.HPSF;
using System.Data.Entity;

namespace CubicFWNet.Mvc.Controllers
{

    public class StorageTableController : ControllerBase
    {
        private StorageTableApp _storageTableApp = new StorageTableApp();
        private InventoryApp _inventoryApp = new InventoryApp();
        private InventoryUerApp _inventoryUerApp = new InventoryUerApp();
        private InvoiceApp _invoiceApp = new InvoiceApp();
        private ProductApp _productApp = new ProductApp();
        private OrderApp _orderApp = new OrderApp();
        private OrderProductApp _orderProductApp = new OrderProductApp();
        private MaterialFormatApp _materialFormatApp = new MaterialFormatApp();
        private OperateRecordApp _operateRecordApp = new OperateRecordApp();
        private InventoryChangeApp _inventoryChangeApp = new InventoryChangeApp();
        private InventoryChangeApplyApp _inventoryChangeApplyApp = new InventoryChangeApplyApp();
        private StorageApp _storageApp = new StorageApp();
        private TakeLogApp _takeLogApp = new TakeLogApp();
        private UserApp _userApp = new UserApp();

        private CategoryApp _categoryApp = new CategoryApp();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询产品入库申请
        /// </summary>
        /// <returns></returns>
        public ActionResult PutInStorage(int page = 1, int type = 0, string start = "", string end = "", string name = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            IEnumerable<StorageTableView> ls = _storageTableApp.GetList(type, _start, _end, name).ToPagedList(page, 10);
            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            return View(ls);
        }

        ///// <summary>
        ///// 查询产品出库申请
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult OutStorage(int page = 1, int type = 0, int proType = 0, string start = "", string end = "", string name = "")
        //{
        //    DateTime _start = Convert.ToDateTime("2017-1-1");
        //    DateTime _end = DateTime.Now.AddDays(1);
        //    if (start != "")
        //    {
        //        _start = Convert.ToDateTime(start);
        //    }
        //    if (end != "")
        //    {
        //        _end = Convert.ToDateTime(end);
        //    }
        //    //IEnumerable<StorageTableView> ls = _storageTableApp.GetList(1, 1, -1, _start, _end, name).ToPagedList(page, 10);
        //    IEnumerable<StorageTableView> ls = _storageTableApp.GetList(type, proType, _start, _end, name).ToPagedList(page, 10);
        //    ViewBag.Start = _start.ToString("yyyy-MM-dd");
        //    ViewBag.End = _end.ToString("yyyy-MM-dd");
        //    ViewBag.Name = name;
        //    return View(ls);
        //}

        /// <summary>
        /// 提交入库申请
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPutInStorage()
        {
            StorageTableView st = new StorageTableView();
            string str = Request.QueryString["SID"];
            List<OrderRelationView> lsOrder = new List<OrderRelationView>();
            if (str != null)
            {
                Guid id = new Guid(str);
                st = _storageTableApp.GetFullInfo(id);
                int otherType = st.OtherType;
                Guid otherID = new Guid(st.OtherID.ToString());
                //采购入库
                if (otherType == 1)
                {
                    //获取订单列表
                    lsOrder = _storageTableApp.GetOrderByRealtion("PurchaseCompose-Order", otherID, st.ProductId).ToList();
                }
                //生产入库
                else if (otherType == 2)
                {
                    lsOrder = _storageTableApp.GetOrderByRealtion("Worksheet-Order", otherID, st.ProductId).ToList();
                }
                if (lsOrder.Count == 0)
                {
                    OrderRelationView newOrder = GetNewOrderRelationView();
                    lsOrder.Add(newOrder);
                }
            }

            ViewBag.OrderList = lsOrder;
            ViewBag.RealName = operatorModel.FamilyName;
            ViewBag.ST = st;
            return View();
        }

        /// <summary>
        /// 提交入库申请[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPutInStorage(FormCollection fc)
        {
            Guid id = new Guid(fc["SID"]);
            StorageTable st = _storageTableApp.GetInfo(id);
            //st.Status = 1;
            st.Memo = fc["Memo"];
            st.Amount = Convert.ToDecimal(fc["Amount"]);
            st.CreateTime = DateTime.Now;
            st.CreatorId = operatorModel.UserId;
            st.CreatorName = operatorModel.FamilyName;

            int res = _storageTableApp.Update(st);
            if (res > 0)
            {
                //1. 提交产品总库存           
                Inventory inv = _inventoryApp.GetInfoByPID(st.ProductId, 0);
                if (null != inv)
                {
                    inv.Amount += st.Amount;
                    _inventoryApp.Update(inv);
                }
                else
                {
                    inv = new Inventory();
                    inv.Id = Guid.NewGuid();
                    inv.Amount = st.Amount;
                    inv.ProuctId = st.ProductId;
                    _inventoryApp.Add(inv);

                    OperateRecord o = new OperateRecord();
                    o.ItemId = st.Id;
                    o.TypeId = 21;
                    o.EndTime = DateTime.Now;
                    o.CreatorId = operatorModel.UserId;
                    o.CreatorName = operatorModel.FamilyName;
                    _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志
                }

                //2. 提交订单所对应产品库存
                string proList = fc["ProData"];
                JavaScriptSerializer js = new JavaScriptSerializer();
                List<InventoryOrder> ls = js.Deserialize<List<InventoryOrder>>(proList);
                foreach (var obj in ls)
                {
                    InventoryUer iu = _inventoryUerApp.GetInfoByOrder(obj.OrderID, obj.ProductID);
                    if (iu != null)
                    {
                        iu.CreateTime = DateTime.Now;
                        iu.Amount += obj.Amount;
                        _inventoryUerApp.Update(iu);
                    }
                    else
                    {
                        iu = new InventoryUer();
                        iu.Id = Guid.NewGuid();
                        iu.CreateTime = DateTime.Now;
                        iu.Amount = obj.Amount;
                        iu.ProductID = obj.ProductID;
                        iu.OrderID = obj.OrderID;
                        iu.UserID = obj.UserID;
                        _inventoryUerApp.Add(iu);
                    }
                }
                return RedirectToAction("PutInStorageRecord", "StorageTable");
            }
            return View();
        }

        /// <summary>
        /// 提交出库申请
        /// </summary>
        /// <returns></returns>
        public ActionResult AddOutStorage()
        {
            StorageTableView st = new StorageTableView();
            string str = Request.QueryString["SID"];
            if (str != null)
            {
                Guid id = new Guid(str);
                st = _storageTableApp.GetFullInfo(id);
            }
            ViewBag.RealName = operatorModel.FamilyName;
            ViewBag.ST = st;
            return View();
        }


        ///// <summary>
        ///// 提交出库申请[提交数据]
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult AddOutStorage(FormCollection fc)
        //{
        //    Guid id = new Guid(fc["SID"]);
        //    StorageTableView stw = _storageTableApp.GetFullInfo(id);
        //    StorageTable st = _storageTableApp.GetInfo(id);
        //    //st.Status = 1;
        //    st.Memo = fc["Memo"];
        //    st.Amount = Convert.ToDecimal(fc["Amount"]);
        //    st.CreateTime = DateTime.Now;
        //    st.CreatorId = operatorModel.UserId;
        //    st.CreatorName = operatorModel.FamilyName;

        //    Inventory inv = _inventoryApp.GetInfoByPID(st.ProductId);
        //    InventoryUer invu = _inventoryUerApp.GetInventoryByOrder(new Guid(st.OrderId.ToString()), st.ProductId);
        //    //Invoice invoice = _invoiceApp.GetSingleInvoice(st.InvoiceID);
        //    if (null != inv && null != invu)
        //    {
        //        decimal tmp1 = inv.Amount - st.Amount;
        //        decimal tmp2 = invu.Amount - st.Amount;
        //        if (tmp1 < 0 || tmp2 < 0)
        //        {
        //            ViewBag.Info = "库存不足";
        //        }
        //        else
        //        {
        //            //更新总库存
        //            inv.Amount = tmp1;
        //            _inventoryApp.Update(inv);

        //            //更新订单库存
        //            invu.Amount = tmp2;
        //            _inventoryUerApp.Update(invu);

        //            //更新出库申请
        //            _storageTableApp.Update(st);

        //            //更新发货单状态
        //            //if (_storageTableApp.GetOutCount(st.InvoiceID))
        //            //{
        //            //    invoice.Status = 1;
        //            //    _invoiceApp.Update(invoice);
        //            //}


        //            //更新操作记录
        //            OperateRecord o = new OperateRecord();
        //            o.ItemId = st.Id;
        //            o.TypeId = 22;
        //            o.EndTime = DateTime.Now;
        //            o.CreatorId = operatorModel.UserId;
        //            o.CreatorName = operatorModel.FamilyName;
        //            _operateRecordApp.UpdateOperateRecord(o);
        //            return RedirectToAction("OutStorageRecord", "StorageTable");
        //        }
        //    }
        //    else
        //    {
        //        ViewBag.Info = "库存不足";
        //    }
        //    ViewBag.RealName = operatorModel.FamilyName;
        //    ViewBag.ST = stw;
        //    return View();
        //}

        /// <summary>
        /// 导出产品库存记录
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult DownloadInventoryProduct(int categoryid = 0, int storageId = 0, string name = "")
        {
            IEnumerable<InventoryView> ls = _inventoryApp.GetInventoryList(categoryid, storageId, name);

            //return ToExcel2(ExcelHelper.ToTable(ls), "产品库存.xls", DateTime.Now.ToString("D"));
            return ToExcelInventoryProduct(ls, "产品库存.xls", DateTime.Now.ToString("D"));
        }

        public ActionResult ToExcelInventoryProduct(IEnumerable<InventoryView> list, string title, string sheetName)
        {
            //FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            MemoryStream ms = new MemoryStream();
            IWorkbook workBook = new HSSFWorkbook();
            //this.sheetName = this.sheetName.IsEmpty() ? "sheet1" : this.sheetName;
            ISheet sheet = workBook.CreateSheet(sheetName);

            //处理表格标题
            IRow row = sheet.CreateRow(0);
            //row.CreateCell(0).SetCellValue(title);
            //sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
            //row.Height = 500;

            ICellStyle cellStyle = workBook.CreateCellStyle();
            IFont font = workBook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 17;
            cellStyle.SetFont(font);
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.Alignment = HorizontalAlignment.Center;
            //  row.Cells[0].CellStyle = cellStyle;

            //row = sheet.CreateRow(1);
            row.CreateCell(0).SetCellValue("产品编号");
            row.CreateCell(1).SetCellValue("产品名称");
            row.CreateCell(2).SetCellValue("类型");
            row.CreateCell(3).SetCellValue("尺寸宽一毫米");
            row.CreateCell(4).SetCellValue("尺寸长一毫米");
            row.CreateCell(5).SetCellValue("规格");
            row.CreateCell(6).SetCellValue("基本单位");
            row.CreateCell(7).SetCellValue("期末数据");
            row.CreateCell(8).SetCellValue("库房所在地");
            row.CreateCell(9).SetCellValue("备注");
            var storages = _storageApp.GetList();
            for (int i = 0; i < list.Count(); i++)
            {
                //创建行
                NPOI.SS.UserModel.IRow rowTemp = sheet.CreateRow(i + 1);
                //产品编号
                rowTemp.CreateCell(0).SetCellValue(list.ElementAt(i).Number);
                //产品名称
                rowTemp.CreateCell(1).SetCellValue(list.ElementAt(i).ProuctName);
                //分类
                //rowTemp.CreateCell(2).SetCellValue(list.ElementAt(i).Type);
                rowTemp.CreateCell(2).SetCellValue(list.ElementAt(i).CategoryName);
                //尺寸宽一毫米
                rowTemp.CreateCell(3).SetCellValue(list.ElementAt(i).SizeWidth.ToDouble());
                //尺寸长一毫米
                rowTemp.CreateCell(4).SetCellValue(list.ElementAt(i).SizeLenth.ToDouble());
                //规格
                rowTemp.CreateCell(5).SetCellValue(list.ElementAt(i).Format);
                //基本单位
                rowTemp.CreateCell(6).SetCellValue(list.ElementAt(i).Unit);
                //期末数据
                rowTemp.CreateCell(7).SetCellValue(list.ElementAt(i).Amount.ToInt());
                //库房所在地
                if (list.ElementAt(i).StorageId != 0)
                {
                    var storageName = storages.First(a => a.Id == list.ElementAt(i).StorageId).Name;
                    if (!string.IsNullOrEmpty(storageName))
                    {
                        rowTemp.CreateCell(8).SetCellValue(storageName);
                    }
                    else
                    {
                        rowTemp.CreateCell(8).SetCellValue("");
                    }
                }
                else
                {
                    rowTemp.CreateCell(8).SetCellValue("");
                }
                //rowTemp.CreateCell(8).SetCellValue(list.ElementAt(i).StorageName);
                //备注
                rowTemp.CreateCell(9).SetCellValue(list.ElementAt(i).Memo);
            }
            workBook.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", title);

        }


        /// <summary>
        /// 导入文件
        /// </summary>
        public ActionResult ImportExcel(HttpPostedFileBase file)
        {
            var fileName = file.FileName;
            var filePath = Server.MapPath(string.Format("~/{0}", "File"));

            file.SaveAs(Path.Combine(filePath, fileName));

            XSSFWorkbook hssfworkbook;
            try
            {
                using (FileStream file1 = new FileStream(Path.Combine(filePath, fileName), FileMode.Open, FileAccess.Read))
                {
                    hssfworkbook = new XSSFWorkbook(file1);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            for (int k = 0; k < 10; k++)
            {
                ISheet sheet = null;
                try
                {
                    sheet = hssfworkbook.GetSheetAt(k);
                }
                catch (Exception e)
                {
                    break;
                }
                if (sheet != null)
                {
                    DataTable table = new DataTable();
                    IRow headerRow = sheet.GetRow(0);//第一行为标题行
                    if (headerRow == null)
                    {
                        break;
                    }
                    int cellCount = headerRow.LastCellNum;
                    //
                    //var LastCellNum = PhysicalNumberOfCells;
                    int rowCount = sheet.LastRowNum;
                    //
                    //var LastRowNum = PhysicalNumberOfRows - 1;

                    List<Product> products = new List<Product>();

                    //handling header.
                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                        table.Columns.Add(column);
                    }
                    for (int i = sheet.FirstRowNum + 1; i <= rowCount; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        DataRow dataRow = table.NewRow();

                        var name = "";
                        var category = "";
                        var number = "";
                        string SizeWidth = "";
                        string SizeLenth = "";
                        var Format = "";
                        var Unit = "";
                        decimal amount = 0;
                        //decimal amount1 = 0;
                        var storage = "";
                        //int storageId = 0;
                        var memo = "";

                        if (row != null)
                        {
                            //for (int j = row.FirstCellNum; j < cellCount; j++)
                            //{
                            //    if (row.GetCell(j) != null)
                            //    {
                            //dataRow[j] = GetCellValue(row.GetCell(j));
                            if (row.GetCell(0) == null)
                            {
                                break;
                            }
                            number = row.GetCell(0) != null ? GetCellValue(row.GetCell(0)) : "";
                            name = row.GetCell(1) != null ? GetCellValue(row.GetCell(1)) : "";
                            category = row.GetCell(2) != null ? GetCellValue(row.GetCell(2)) : "";

                            //if (row.GetCell(3) != null)
                            //{
                            //    var width = GetCellValue(row.GetCell(3));
                            //    if (!string.IsNullOrEmpty(width))
                            //    {
                            //        SizeWidth = Convert.ToDecimal(width);
                            //    }
                            //}
                            SizeWidth = row.GetCell(3) != null ? GetCellValue(row.GetCell(3)) : "";

                            //if (row.GetCell(4) != null)
                            //{
                            //    var lenth = GetCellValue(row.GetCell(4));
                            //    if (!string.IsNullOrEmpty(lenth))
                            //    {
                            //        SizeLenth = Convert.ToDecimal(lenth);
                            //    }
                            //}
                            SizeLenth = row.GetCell(4) != null ? GetCellValue(row.GetCell(4)) : "";

                            Format = row.GetCell(5) != null ? GetCellValue(row.GetCell(5)) : "";
                            Unit = row.GetCell(6) != null ? GetCellValue(row.GetCell(6)) : "";
                            if (row.GetCell(7) != null)
                            {
                                var _amount = GetCellValue(row.GetCell(7));
                                if (!string.IsNullOrEmpty(_amount))
                                {
                                    amount = Convert.ToDecimal(_amount);
                                }
                            }
                            //if (k == 1 || k == 7)
                            //{
                            //    if (row.GetCell(8) != null)
                            //    {
                            //        var _amount1 = GetCellValue(row.GetCell(8));
                            //        if (!string.IsNullOrEmpty(_amount1))
                            //        {
                            //            amount1 = Convert.ToDecimal(_amount1);
                            //        }
                            //    }
                            //    storage = row.GetCell(9) != null ? GetCellValue(row.GetCell(9)) : "";
                            //    memo = row.GetCell(10) != null ? GetCellValue(row.GetCell(10)) : "";
                            //}
                            //else
                            //{

                            storage = row.GetCell(8) != null ? GetCellValue(row.GetCell(8)) : "";
                            memo = row.GetCell(9) != null ? GetCellValue(row.GetCell(9)) : "";

                            //}

                            //storageId = Convert.ToInt32(GetCellValue(row.GetCell(9)));
                            //    }
                            //    if (cellCount == 9)
                            //    {
                            //        memo = GetCellValue(row.GetCell(9));
                            //    }
                            //}
                        }
                        //table.Rows.Add(dataRow);
                        var categoryModel = _categoryApp.GetByName(category);
                        //var type = 1;
                        //if (category.Trim() == ProductTypeConfig.YuanCai)
                        //{
                        //    type = 2;
                        //}
                        //插入数据库
                        if (!string.IsNullOrEmpty(number))
                        {
                            var product = _productApp.GetByNumber(number);
                            if (product != null)
                            {
                                try
                                {
                                    using (YJXErpContext db = new YJXErpContext())
                                    {
                                        product.Name = name;
                                        product.Status = 1;
                                        //product.Type = type;
                                        product.CategoryId = categoryModel != null ? categoryModel.Id : 0;
                                        product.Number = number;
                                        product.SizeWidth = SizeWidth;
                                        product.SizeLenth = SizeLenth;
                                        product.Format = Format;
                                        product.Unit = Unit;
                                        product.CreatorId = operatorModel.UserId;
                                        product.CreatorName = operatorModel.FamilyName;
                                        product.Memo = memo;
                                        db.Entry(product).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                }
                                catch (Exception e)
                                {
                                    throw e;
                                }
                                var storageModel = _storageApp.GetByName(storage);
                                var _inventory = _inventoryApp.GetInfoByPID(product.Id, storageModel != null ? storageModel.Id : 0);
                                if (_inventory == null)
                                {
                                    _inventory = new Inventory
                                    {
                                        Id = Guid.NewGuid(),
                                        Amount = amount,
                                        //Amount_Init = amount1,
                                        Memo = memo,
                                        ProuctId = product.Id,
                                        StorageId = storageModel != null ? storageModel.Id : 0,
                                    };
                                    _inventoryApp.Add(_inventory);
                                }
                                else
                                {
                                    using (YJXErpContext db = new YJXErpContext())
                                    {
                                        _inventory.Amount = amount;
                                        //_inventory.Amount_Init = amount1;
                                        _inventory.Memo = memo;
                                        _inventory.ProuctId = product.Id;
                                        _inventory.StorageId = storageModel != null ? storageModel.Id : 0;
                                        db.Entry(_inventory).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                }
                            }
                            else
                            {
                                product = new Product();
                                product.Id = Guid.NewGuid();
                                product.Status = 1;
                                product.Name = name;
                                //product.Type = type;
                                product.Id = Guid.NewGuid();
                                product.CategoryId = categoryModel != null ? categoryModel.Id : 0;
                                product.Number = number;
                                product.SizeWidth = SizeWidth;
                                product.SizeLenth = SizeLenth;
                                product.Format = Format;
                                product.Unit = Unit;
                                product.CreatorName = operatorModel.FamilyName;
                                product.CreatorId = operatorModel.UserId;
                                product.CreateTime = DateTime.Now;
                                product.Memo = memo;
                                _productApp.Insert(product);
                                var storageModel = _storageApp.GetByName(storage);
                                _inventoryApp.Add(new Inventory
                                {
                                    Id = Guid.NewGuid(),
                                    Amount = amount,
                                    Memo = memo,
                                    ProuctId = product.Id,
                                    StorageId = storageModel != null ? storageModel.Id : 0,
                                });

                            }
                        }
                    }
                }
            }
            return Json("上传成功");
        }


        /// <summary>
        /// 根据Excel列类型获取列的值
        /// </summary>
        /// <param name="cell">Excel列</param>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                case CellType.Unknown:
                default:
                    return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }

        /// <summary>
        ///  库房管理查看
        /// </summary>
        /// <param name="page"></param>
        /// <param name="type">type : 1成品   2原材</param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult InventoryProduct(int page = 1, int categoryid = 0, int storageId = 0,string name = "")
        {
            ViewBag.Name = name;

            var category = _categoryApp.GetList();
            category.Insert(0, new Category() { Id = 0, Name = "全部" });
            ViewBag.CategoryList = category;
            ViewBag.CategoryId = categoryid;
            ViewBag.StorageId = storageId;

            //ViewBag.UserModules = operatorModel.UserModules;

            IEnumerable<InventoryView> ls = _inventoryApp.GetInventoryList(categoryid, storageId, name).ToPagedList(page, 10);
            var storages = _storageApp.GetList();
            foreach (var item in ls)
            {
                if (item.StorageId != 0)
                {
                    item.StorageName = storages.First(a => a.Id == item.StorageId).Name;
                }
            }
            storages.Insert(0, new Storage() { Id = 0, Name = "全部" });
            ViewBag.Storages = storages;

            return View(ls);
        }

        public ActionResult TakeProduct(int storageId = 0, int categoryid = 0, string name = "")
        {
            IEnumerable<InventoryView> ls = _inventoryApp.GetInventoryList(categoryid, storageId, name).Where(items => items.StorageId == storageId);
            var storages = _storageApp.GetList();
            foreach (var item in ls)
            {
                if (item.StorageId != 0)
                {
                    item.StorageName = storages.First(a => a.Id == item.StorageId).Name;
                }
            }
            storages.Insert(0, new Storage() { Id = 0, Name = "全部" });
            ViewBag.StorageId = storageId;
            ViewBag.Name = name;
            ViewBag.Storages = storages;
            return View(ls);
        }

        /// <summary>
        /// 更新库存
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateTakeProduct(Guid id, decimal amount, decimal camount, string memo)
        {
            //更新库存
            Inventory entity = _inventoryApp.GetInfo(id);
            entity.Amount = amount;
            _inventoryApp.Update(entity);

            TakeLog takeLog = new TakeLog()
            {
                Id = Guid.NewGuid(),
                InventoryId = id,
                ProductId = entity.ProuctId,
                Memo = memo,
                Comment = String.Format("{0}于{1},把库存由{2}改为{3}", operatorModel.FamilyName, DateTime.Now, camount, amount)
            };
            _takeLogApp.Add(takeLog);
            return Json(1);
        }

        public ActionResult TakeMaterial(int storageId = 0, int categoryid = 0, string name = "")
        {
            IEnumerable<InventoryView> ls = _inventoryApp.GetInventoryList(categoryid, storageId, name);
            IEnumerable<Storage> storages = _storageApp.GetList();
            foreach (var item in ls)
            {
                if (item.StorageId != 0)
                {
                    item.StorageName = storages.First(a => a.Id == item.StorageId).Name;
                }
            }
            ViewBag.Name = name;
            ViewBag.Storages = storages;
            return View(ls);
        }
        //public JsonResult UpdateTakeMaterial(Guid id, decimal amount,  string memo)
        //{
        //    //更新库存
        //    Inventory entity = _inventoryApp.GetInfo(id);
        //    //entity.Area = amount;   //没搞明白原料库为啥更新area，而不是amount 2019-12-21 sunjian
        //    _inventoryApp.Update(entity);

        //    TakeLog takeLog = new TakeLog()
        //    {
        //        Id = Guid.NewGuid(),
        //        InventoryId = id,
        //        ProductId = entity.ProuctId,
        //        Memo = memo,
        //        Comment = String.Format("{0}于{1},把库存由{2}", operatorModel.FamilyName, DateTime.Now, amount)
        //    };
        //    _takeLogApp.Add(takeLog);
        //    return Json(1);
        //}

        /// <summary>
        /// 原料库存
        /// </summary>
        /// <returns></returns>
        public ActionResult InventoryMaterial(int page = 1, int storageId = 0, int categoryid = 0, string name = "")
        {
            IEnumerable<InventoryView> ls = _inventoryApp.GetInventoryList(categoryid, storageId, name).ToPagedList(page, 10);
            ViewBag.Name = name;
            return View(ls);
        }

        /// <summary>
        /// 产品入库记录
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult PutInStorageRecord(int page = 1, string start = "", string end = "", string name = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }
            name = name.Trim();
            IEnumerable<StorageTableView> ls = _storageTableApp.GetList(2, _start, _end, name).ToPagedList(page, 10);
            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            return View(ls);
        }

        /// <summary>
        /// 导出入库记录
        /// </summary>
        /// <param name="type">1：出库  2：入库</param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult DownloadPutInStorageRecord(int type = 1, string start = "", string end = "", string name = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }
            var types = type == 1 ? "出" : "入";
            IEnumerable<StorageTableView> ls = _storageTableApp.GetList(type: type, start: _start, end: _end, name: name);
            return ToExcelPutInStorageRecord(ls, $"{types}库记录{_start.ToString("yyyy-MM-dd")}_{_end.ToString("yyyy-MM-dd")}.xls", DateTime.Now.ToString("D"));
        }

        public ActionResult ToExcelPutInStorageRecord(IEnumerable<StorageTableView> list, string title, string sheetName)
        {
            MemoryStream ms = new MemoryStream();
            IWorkbook workBook = new HSSFWorkbook();
            ISheet sheet = workBook.CreateSheet(sheetName);

            //处理表格标题
            IRow row = sheet.CreateRow(0);

            ICellStyle cellStyle = workBook.CreateCellStyle();
            IFont font = workBook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 17;
            cellStyle.SetFont(font);
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.Alignment = HorizontalAlignment.Center;
            //  row.Cells[0].CellStyle = cellStyle;

            //row = sheet.CreateRow(1);
            row.CreateCell(0).SetCellValue("产品编号");
            row.CreateCell(1).SetCellValue("产品名称");
            row.CreateCell(2).SetCellValue("入库数量");
            row.CreateCell(3).SetCellValue("入库时间");
            row.CreateCell(4).SetCellValue("尺寸宽一毫米");
            row.CreateCell(5).SetCellValue("尺寸长一毫米");
            row.CreateCell(6).SetCellValue("规格");
            row.CreateCell(7).SetCellValue("价格");
            row.CreateCell(8).SetCellValue("基本单位");
            row.CreateCell(9).SetCellValue("总库存量");
            row.CreateCell(11).SetCellValue("库房所在地");
            row.CreateCell(12).SetCellValue("订单号");
            row.CreateCell(13).SetCellValue("备注");
            for (int i = 0; i < list.Count(); i++)
            {
                //创建行
                NPOI.SS.UserModel.IRow rowTemp = sheet.CreateRow(i + 1);
                //产品编号
                rowTemp.CreateCell(0).SetCellValue(list.ElementAt(i).Number);
                //产品名称
                rowTemp.CreateCell(1).SetCellValue(list.ElementAt(i).ProductName);
                rowTemp.CreateCell(2).SetCellValue(list.ElementAt(i).Amount.ToInt());
                rowTemp.CreateCell(3).SetCellValue(list.ElementAt(i).ProductName);
                //尺寸宽一毫米
                rowTemp.CreateCell(4).SetCellValue(list.ElementAt(i).Width.ToDouble());
                //尺寸长一毫米
                rowTemp.CreateCell(5).SetCellValue(list.ElementAt(i).Length.ToDouble());
                //规格
                rowTemp.CreateCell(6).SetCellValue(list.ElementAt(i).Format);
                //价格
                rowTemp.CreateCell(7).SetCellValue(list.ElementAt(i).Price.ToString("#0.0000"));
                //基本单位
                rowTemp.CreateCell(8).SetCellValue(list.ElementAt(i).Unit);
                //期末数据
                rowTemp.CreateCell(9).SetCellValue(list.ElementAt(i).Total.ToDouble());
                //库房所在地
                rowTemp.CreateCell(10).SetCellValue(list.ElementAt(i).StorageName);
                rowTemp.CreateCell(11).SetCellValue(list.ElementAt(i).OrderNumber);
                //备注
                rowTemp.CreateCell(12).SetCellValue(list.ElementAt(i).Memo);
            }
            workBook.Write(ms);

            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", title);

        }



        ///// <summary>
        ///// 原料入库记录
        ///// </summary>
        ///// <param name="page"></param>
        ///// <returns></returns>
        //public ActionResult PutInMaterialRecord(int page = 1, string start = "", string end = "", string name = "")
        //{
        //    DateTime _start = Convert.ToDateTime("2017-1-1");
        //    DateTime _end = DateTime.Now.AddDays(1);
        //    if (start != "")
        //    {
        //        _start = Convert.ToDateTime(start);
        //    }
        //    if (end != "")
        //    {
        //        _end = Convert.ToDateTime(end);
        //    }

        //    IEnumerable<StorageTableView> ls = _storageTableApp.GetList(2, 2, 1, _start, _end, name).ToPagedList(page, 10);
        //    ViewBag.Start = _start.ToString("yyyy-MM-dd");
        //    ViewBag.End = _end.ToString("yyyy-MM-dd");
        //    ViewBag.Name = name;
        //    return View(ls);
        //}

        /// <summary>
        /// 出库记录
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult OutStorageRecord(int page = 1, string start = "", string end = "", string name = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            IEnumerable<StorageTableView> ls = _storageTableApp.GetList(1, _start, _end, name).ToPagedList(page, 10);
            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            return View(ls);
        }

        ///// <summary>
        ///// 原料出库记录
        ///// </summary>
        ///// <param name="page"></param>
        ///// <returns></returns>
        //public ActionResult OutMaterialRecord(int page = 1, string start = "", string end = "", string name = "")
        //{
        //    DateTime _start = Convert.ToDateTime("2017-1-1");
        //    DateTime _end = DateTime.Now.AddDays(1);
        //    if (start != "")
        //    {
        //        _start = Convert.ToDateTime(start);
        //    }
        //    if (end != "")
        //    {
        //        _end = Convert.ToDateTime(end);
        //    }

        //    IEnumerable<StorageTableView> ls = _storageTableApp.GetList(1, 2, 1, _start, _end, name).ToPagedList(page, 10);
        //    ViewBag.Start = _start.ToString("yyyy-MM-dd");
        //    ViewBag.End = _end.ToString("yyyy-MM-dd");
        //    ViewBag.Name = name;
        //    return View(ls);
        //}

        /// <summary>
        /// 产品入库
        /// </summary>
        /// <returns></returns>
        public ActionResult PutInProduct()
        {
            string pid = Request.QueryString["PID"];
            Product pro = new Product();
            ViewBag.RealName = operatorModel.FamilyName;
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">类型[数据字典] 1：出库 2：入库</param>
        /// <param name="orderNumber"></param>
        /// <param name="pid"></param>
        /// <param name="amount"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PutInProduct(string orderNumber, Guid pid, int storageId, DateTime start, decimal amount, string memo)
        {
            StorageTable st = new StorageTable();
            st.Id = Guid.NewGuid();
            st.Type = 2;
            st.StorageId = storageId;
            st.Time = start;
            st.CreateTime = DateTime.Now;
            st.CreatorId = operatorModel.UserId;
            st.CreatorName = operatorModel.FamilyName;
            st.Amount = amount;
            st.OrderNumber = orderNumber;
            st.ProductId = pid;
            st.Memo = memo;

            //入库记录
            _storageTableApp.Add(st);

            //更新订单对应库存
            //InventoryUer iu = _inventoryUerApp.GetInfoByOrder(new Guid(st.OrderId.ToString()), st.ProductId);
            //if (iu != null)
            //{
            //    iu.CreateTime = DateTime.Now;
            //    iu.Amount += st.Amount;
            //    _inventoryUerApp.Update(iu);
            //}
            //else
            //{
            //    iu = new InventoryUer();
            //    iu.Id = Guid.NewGuid();
            //    iu.CreateTime = DateTime.Now;
            //    iu.Amount = st.Amount;
            //    iu.ProductID = st.ProductId;
            //    iu.OrderID = new Guid(st.OrderId.ToString());
            //    iu.UserID = new Guid(fc["UID"]);
            //    _inventoryUerApp.Add(iu);
            //}

            //更新产品总库存
            Inventory inv = _inventoryApp.GetInfoByPID(st.ProductId, storageId);
            if (null != inv)
            {
                inv.Amount += st.Amount;
                _inventoryApp.Update(inv);
            }
            else
            {
                inv = new Inventory();
                inv.Id = Guid.NewGuid();
                inv.Amount = st.Amount;
                inv.ProuctId = st.ProductId;
                inv.StorageId = st.StorageId;
                _inventoryApp.Add(inv);
            }
            return Json("");
        }

        /// <summary>
        /// 产品出库
        /// </summary>
        /// <returns></returns>
        public ActionResult OutProduct()
        {
            //string pid = Request.QueryString["PID"];
            //Product pro = new Product();
            //List<OrderInfo> orderList = new List<OrderInfo>(); //有库存的订单列表
            //if (pid != null)
            //{
            //    pro = _productApp.GetInfo(new Guid(pid));
            //    orderList = _inventoryUerApp.GetOrderListByProduct(new Guid(pid)).ToList();
            //}
            //List<ProductView> proList = _productApp.GetList(1, 0, "").ToList();

            //公共库存
            //OrderRelationView tmp = GetNewOrderRelationView();
            //OrderInfo ord = new OrderInfo();
            //ord.Id = tmp.OrderId.Value;
            //ord.UserId = tmp.UserId;
            //ord.Number = tmp.Number;
            //ord.SalerName = tmp.UserName;
            //orderList.Add(ord);

            //ViewBag.ProList = proList;
            //ViewBag.OrderList = orderList;
            //ViewBag.Product = pro;
            ViewBag.RealName = operatorModel.FamilyName;
            return View();
        }

        /// <summary>
        /// 提交产品出库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OutProduct(string orderNumber, Guid pid, int storageId, DateTime start, decimal amount, string memo)
        {
            StorageTable st = new StorageTable();
            st.Id = Guid.NewGuid();
            st.StorageId = storageId;
            st.Type = 1;
            //st.Status = 1;
            //st.OtherId = new Guid();
            st.Time = start;
            st.CreateTime = DateTime.Now;
            st.CreatorId = operatorModel.UserId;
            st.CreatorName = operatorModel.FamilyName;
            st.Amount = amount;
            st.OrderNumber = orderNumber;
            st.ProductId = pid;
            st.Memo = memo;

            //更新库存
            //InventoryUer iu = _inventoryUerApp.GetInfoByOrder(new Guid(st.OrderId.ToString()), st.ProductId);
            //if (iu != null && iu.Amount >= st.Amount)
            //{
            //    //更新订单库存
            //    iu.CreateTime = DateTime.Now;
            //    iu.Amount -= st.Amount;
            //    _inventoryUerApp.Update(iu);
            //更新订单发货数量
            //OrderProduct op = _orderProductApp.GetSingleByOrderAndProduct(new Guid(st.OrderId.ToString()), st.ProductId);
            //if (op != null)
            //{
            //    op.SendAmount += st.Amount;
            //    _orderProductApp.Update(op);
            //}

            //出库记录
            //更新产品总库存
            Inventory inv = _inventoryApp.GetInfoByPID(st.ProductId, storageId);
            if (null != inv && inv.Amount >= st.Amount)
            {
                inv.Amount -= st.Amount;
                _inventoryApp.Update(inv);
                _storageTableApp.Add(st);
            }
            else
            {
                return Json("库存不足！");
            }
            return Json("");
        }


        /// <summary>
        /// 修改库存信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditProductStorage(Guid pid, int storageId, decimal amount)
        {
            StorageTable st = new StorageTable();
            st.Id = Guid.NewGuid();
            st.Type = 3;
            st.Time = DateTime.Now;
            st.CreateTime = DateTime.Now;
            st.StorageId = storageId;
            st.CreatorId = operatorModel.UserId;
            st.CreatorName = operatorModel.FamilyName;
            st.Amount = amount;
            st.OrderNumber = "";
            st.ProductId = pid;

            //出库记录
            //更新产品总库存
            Inventory inv = _inventoryApp.GetInfoByPID(st.ProductId, storageId);
            if (null != inv)
            {
                st.Memo = $"修改库存：修改前：{inv.Amount}，修改后：{amount}";
                inv.Amount = st.Amount;
                _inventoryApp.Update(inv);
                _storageTableApp.Add(st);
            }
            return Json("修改库存成功");
        }


        /// <summary>
        /// 删除库存信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string Delete(Guid pid, Guid id)
        {
            StorageTable st = new StorageTable();
            st.Id = Guid.NewGuid();
            st.Type = 4;
            st.Time = DateTime.Now;
            st.CreateTime = DateTime.Now;
            st.CreatorId = operatorModel.UserId;
            st.CreatorName = operatorModel.FamilyName;
            st.OrderNumber = "";

            //出库记录
            //更新产品总库存
            Inventory inv = _inventoryApp.GetInfo(id);
            if (null != inv)
            {
                _inventoryApp.Delete(id);
                return Result.ToJson();
            }
            else
            {
                Result.Status = "error";
                Result.Message = "暂无库存记录";
                return Result.ToJson();
            }
        }

        ///// <summary>
        ///// 原料入库
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult PutInMaterials()
        //{
        //    string pid = Request.QueryString["PID"];
        //    Product pro = new Product();

        //    if (pid != null)
        //    {
        //        pro = _productApp.GetInfo(new Guid(pid));
        //        ViewBag.FormateList = _materialFormatApp.GetListByPID(new Guid(pid)).ToList();
        //    }
        //    List<Product> proList = _productApp.GetList(2, 1, "", "").ToList();

        //    ViewBag.ProList = proList;

        //    ViewBag.Product = pro;
        //    ViewBag.RealName = operatorModel.FamilyName;
        //    return View();
        //}

        ///// <summary>
        ///// 原料入库[提交数据]
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult PutInMaterial(FormCollection fc)
        //{
        //    Guid pid = new Guid(fc["PID"]);
        //    Guid fid = new Guid(fc["Formate"]);
        //    decimal amount = Convert.ToDecimal(fc["Amount"]);
        //    decimal area = 0;

        //    //获取规格库存
        //    MaterialFormat mf = _materialFormatApp.GetInfo(fid);
        //    if (mf != null)
        //    {
        //        //更新规格库存
        //        mf.Amount += amount;
        //        area = (mf.Width * mf.Length * amount / 1000000);
        //        mf.Area += area;
        //        _materialFormatApp.Update(mf);

        //        //更新总库存
        //        Inventory inv = _inventoryApp.GetInfoByPID(pid);
        //        if (null != inv)
        //        {
        //            inv.Amount += amount;
        //            inv.Area += area;
        //            _inventoryApp.Update(inv);
        //        }
        //        else
        //        {
        //            inv = new Inventory();
        //            inv.Id = Guid.NewGuid();
        //            inv.Amount = amount;
        //            inv.ProuctId = pid;
        //            inv.Area = area;
        //            _inventoryApp.Add(inv);
        //        }

        //        //添加入库记录
        //        StorageTable st = new StorageTable();
        //        st.Id = Guid.NewGuid();
        //        st.Type = 2;
        //        //st.Status = 1;
        //        //st.OtherId = new Guid();
        //        //st.ApplyTime = DateTime.Now;
        //        st.CreateTime = DateTime.Now;
        //        st.CreatorId = operatorModel.UserId;
        //        st.CreatorName = operatorModel.FamilyName;
        //        st.Amount = amount;
        //        st.OrderId = new Guid();
        //        st.ProductId = pid;
        //        st.Memo = fc["Memo"];
        //        //st.Format = mf.Format;
        //        _storageTableApp.Add(st);

        //        return RedirectToAction("PutInMaterialRecord", "StorageTable");
        //    }

        //    return View();
        //}

        ///// <summary>
        ///// 原料出库 Type = 2 主料
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult OutMaterial()
        //{
        //    string pid = Request.QueryString["PID"];
        //    Product pro = new Product();

        //    if (pid != null)
        //    {
        //        pro = _productApp.GetInfo(new Guid(pid));
        //        ViewBag.FormateList = _materialFormatApp.GetListByPID(new Guid(pid)).ToList();
        //    }
        //    List<Product> proList = _productApp.GetList(2, 1, "", "").ToList();

        //    ViewBag.ProList = proList;

        //    ViewBag.Product = pro;
        //    ViewBag.RealName = operatorModel.FamilyName;
        //    return View();
        //}

        ///// <summary>
        ///// 原料出库[提交数据]
        ///// </summary>
        ///// <param name="fc"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult OutMaterial(FormCollection fc)
        //{
        //    Guid pid = new Guid(fc["PID"]);
        //    Guid fid = new Guid(fc["Formate"]);
        //    decimal amount = Convert.ToDecimal(fc["Amount"]);
        //    decimal area = 0;

        //    //获取规格库存
        //    MaterialFormat mf = _materialFormatApp.GetInfo(fid);

        //    //判断是否有足够库存
        //    if (mf != null && mf.Amount >= amount)
        //    {
        //        //更新规格库存
        //        mf.Amount -= amount;
        //        area = (mf.Width * mf.Length * amount / 1000000);
        //        mf.Area -= area;
        //        _materialFormatApp.Update(mf);

        //        //更新总库存
        //        Inventory inv = _inventoryApp.GetInfoByPID(pid);
        //        if (null != inv)
        //        {
        //            inv.Amount -= amount;
        //            inv.Area -= area;
        //            _inventoryApp.Update(inv);
        //        }

        //        //添加出库记录
        //        StorageTable st = new StorageTable();
        //        st.Id = Guid.NewGuid();
        //        st.Type = 1;
        //        //st.Status = 1;
        //        //st.OtherId = new Guid();
        //        //st.ApplyTime = DateTime.Now;
        //        st.CreateTime = DateTime.Now;
        //        st.CreatorId = operatorModel.UserId;
        //        st.CreatorName = operatorModel.FamilyName;
        //        st.Amount = amount;
        //        st.OrderId = new Guid();
        //        st.ProductId = pid;
        //        st.Memo = fc["Memo"];
        //        //st.Format = mf.Format;
        //        _storageTableApp.Add(st);

        //        return RedirectToAction("OutMaterialRecord", "StorageTable");
        //    }

        //    else
        //    {
        //        Product pro = new Product();
        //        pro = _productApp.GetInfo(pid);
        //        ViewBag.FormateList = _materialFormatApp.GetListByPID(pid).ToList();
        //        List<Product> proList = _productApp.GetList(2, 1, "", "").ToList();

        //        ViewBag.ProList = proList;

        //        ViewBag.Product = pro;
        //        ViewBag.RealName = operatorModel.FamilyName;
        //        ViewBag.Info = "库存不足！";
        //    }

        //    return View();
        //}

        /// <summary>
        /// 库存修改记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderStorageTable(Guid pid, int sid)
        {
            List<StorageTableView> ls = _storageTableApp.GetList(3, pid, sid).ToList();
            //ViewBag.NoOrder = GetNewOrderRelationView();
            return View(ls);
        }

        /// <summary>
        /// 订单库存列表
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderInventory(Guid pid)
        {
            List<InventoryUserView> ls = _inventoryUerApp.GetListByProduct(pid).ToList();
            ViewBag.NoOrder = GetNewOrderRelationView();
            return View(ls);
        }

        /// <summary>
        /// 原料规格库存
        /// </summary>
        /// <returns></returns>
        public ActionResult MaterialInventoryFormat()
        {
            string id = Request.QueryString["PID"];
            ViewBag.PID = id;
            IEnumerable<MaterialFormat> ls = _materialFormatApp.GetListByPID(new Guid(id));
            return View(ls);
        }

        /// <summary>
        /// 转库存
        /// </summary>
        /// <returns></returns>
        public ActionResult ChangeInventory(string id)
        {
            Guid invID = new Guid(id);
            InventoryUserView invUser = _inventoryUerApp.GetInventoryUserByID(invID);
            List<OrderInfo> orderList = _orderApp.GetList(Convert.ToDateTime("2017-1-1"), DateTime.Now, 3, 0, "", "", "").ToList();

            ViewBag.InventoryUser = invUser;
            ViewBag.OrderList = orderList;
            ViewBag.RealName = operatorModel.FamilyName;
            ViewBag.NoOrder = GetNewOrderRelationView();
            return View();
        }


        /// <summary>
        /// 转库存【提交数据】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangeInventory(FormCollection fc)
        {
            Guid invID = new Guid(fc["InventoryUser"]);
            Guid oID = new Guid(fc["Order"]);
            InventoryUserView inv = _inventoryUerApp.GetInventoryUserByID(invID);
            OrderInfo order = _orderApp.GetFullInfo(oID);
            decimal amount = Convert.ToDecimal(fc["Amount"]);
            if (amount > inv.Amount || amount <= 0)
            {
                ViewBag.Info = "请输入正确的数量！";
                return View();
            }

            InventoryUer invOut = _inventoryUerApp.GetInfoByOrder(inv.OrderID, inv.ProductID);
            InventoryUer invIn = _inventoryUerApp.GetInfoByOrder(order.Id, inv.ProductID);

            //更新转出者库存
            invOut.Amount -= amount;
            _inventoryUerApp.Update(invOut);

            //更新转入者库存
            if (invIn != null)
            {
                invIn.Amount += amount;
                _inventoryUerApp.Update(invIn);
            }
            else
            {
                invIn = new InventoryUer();
                invIn.Id = Guid.NewGuid();
                invIn.Amount = amount;
                invIn.CreateTime = DateTime.Now;
                invIn.OrderID = order.Id;
                invIn.ProductID = inv.ProductID;
                invIn.UserID = new Guid(order.UserId.ToString());

                _inventoryUerApp.Add(invIn);
            }

            //记录转库存记录
            InventoryChange invChange = new InventoryChange();
            invChange.Id = Guid.NewGuid();
            invChange.Amount = amount;
            invChange.CreatorID = operatorModel.UserId;
            invChange.CreateTime = DateTime.Now;
            //invChange.OrderIn = invIn.OrderID;
            //invChange.OrderOut = invOut.OrderID;
            invChange.ProductId = inv.ProductID;
            invChange.Memo = fc["Memo"];
            _inventoryChangeApp.Add(invChange);

            return RedirectToAction("InventoryChangeList", "StorageTable");
        }

        /// <summary>
        /// 查询转库存记录
        /// </summary>
        /// <returns></returns>
        public ActionResult InventoryChangeList(string name = "", string start = "", string end = "", int page = 1)
        {
            name = name.Trim();
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }
            IPagedList<InventoryChangeView> ls = _inventoryChangeApp.GetList(name, _start, _end).ToPagedList(page, 10);
            foreach (var item in ls)
            {
                if (item.ConfirmId != null)
                {
                    var user = _userApp.GetForm(item.ConfirmId.Value);
                    item.ConfirmName = user.RealName;
                }
                if (item.OutStorageId != 0)
                {
                    var storage = _storageApp.GetForm(item.OutStorageId);
                    item.OutStorageName = storage.Name;
                }
                item.Amount = Convert.ToInt32(item.Amount);
            }
            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            return View(ls);
        }

        /// <summary>
        /// 查询转库存申请
        /// </summary>
        /// <returns></returns>
        public ActionResult InventoryChangeApplyList(int page = 1)
        {
            IPagedList<InventoryChangeApplyView> ls = _inventoryChangeApplyApp.GetInventoryChangeApplyList().ToPagedList(page, 10);
            return View(ls);
        }

        public JsonResult FinishApply(Guid id)
        {
            InventoryChangeApply ica = _inventoryChangeApplyApp.GetInventoryChangeApplyInfo(id);
            ica.Status = 1;
            _inventoryChangeApplyApp.Update(ica);
            return Json(1);
        }

        private OrderRelationView GetNewOrderRelationView()
        {
            OrderRelationView orv = new OrderRelationView();
            orv.OrderId = new Guid();
            orv.Number = "0";
            orv.CustomeId = new Guid();
            orv.CustomerName = "无";
            orv.UserId = new Guid();
            orv.UserName = "公共库存，与销售(订单)无关联";
            orv.ProductName = "无";
            orv.CusProName = "无";
            return orv;
        }


        #region  调库存

        /// <summary>
        /// 确认订单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InventoryChange(InventoryChange model)
        {
            //插入“转库存”
            Inventory inv = _inventoryApp.GetInfoByPID(model.ProductId, model.OutStorageId);
            if (null != inv && inv.Amount >= model.Amount)
            {
                inv.Amount -= model.Amount;
                _inventoryApp.Update(inv);
            }
            else
            {
                return Json("库存不足！");
            }
            model.Id = Guid.NewGuid();
            model.CreateTime = DateTime.Now;
            model.CreatorID = operatorModel.UserId;
            _inventoryChangeApp.Add(model);
            return Json("已调库");
        }

        /// <summary>
        /// 确认订单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CopyProductStorage(InventoryChange model)
        {
            //插入“转库存”
            Inventory inv = _inventoryApp.GetInfoByPID(model.ProductId, model.InStorageId);
            if (null != inv)
            {
                inv.Amount = model.Amount;
                _inventoryApp.Update(inv);
            }
            else
            {
                inv = new Inventory();
                inv.Id = Guid.NewGuid();
                inv.Amount = model.Amount;
                inv.StorageId = model.InStorageId;
                inv.ProuctId = model.ProductId;
                _inventoryApp.Add(inv);
            }
            model.Id = Guid.NewGuid();
            model.CreateTime = DateTime.Now;
            model.CreatorID = operatorModel.UserId;
            _inventoryChangeApp.Add(model);

            return Json("已复制库存");
        }

        /// <summary>
        /// 确认订单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InventoryChangeConfirm(Guid id)
        {
            //插入“转库存”
            InventoryChange model = _inventoryChangeApp.Get(id);
            if (model.Confirm == 1)
            {
                return Json("已调库");
            }
            model.Confirm = 1;
            model.ConfirmTime = DateTime.Now;
            model.ConfirmId = operatorModel.UserId;
            _inventoryChangeApp.Update(model);

            //添加库存
            Inventory inv = _inventoryApp.GetInfoByPID(model.ProductId, model.InStorageId);
            if (null != inv)
            {
                inv.Amount += model.Amount;
                _inventoryApp.Update(inv);
            }
            else
            {
                inv = new Inventory();
                inv.Id = Guid.NewGuid();
                inv.Amount = model.Amount;
                inv.StorageId = model.InStorageId;
                inv.ProuctId = model.ProductId;
                _inventoryApp.Add(inv);
            }

            return Json("已调库");
        }


        /// <summary>
        /// 确认订单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InventoryChangeError(Guid id, string memo)
        {
            //插入“转库存”
            InventoryChange model = _inventoryChangeApp.Get(id);
            model.Confirm = -1;
            model.Memo = memo;
            model.ConfirmTime = DateTime.Now;
            model.ConfirmId = operatorModel.UserId;
            _inventoryChangeApp.Update(model);
            return Json("已调库");
        }

        #endregion

    }
}